package com.cxs.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigInteger;
import java.util.Collection;

/**
 * standard策略之自定义精确分表算法类
 * <p>
 * 执行比如 select * from t_order_? where order_id = ?
 */
public class MyPreciseTableShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    /**
     * 精确分表方法
     * 返回值就是需要检索的表名称
     *
     * @param availableTargetNames 所有的真实表名称集合
     * @param shardingValue        过滤条件
     * @return
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        // 获取逻辑表名称
        String logicTableName = shardingValue.getLogicTableName();
        // 分片键 / 过滤字段的值
        Long orderId = shardingValue.getValue();

        //实现算法思路还是这个表达式： t_order_$->{order_id % 2 + 1}
        BigInteger shardingValueB = BigInteger.valueOf(orderId);
        // 实现order_id % 2 + 1逻辑, 返回计算后得到的真实表名称的数字: 1或者2
        BigInteger resB = (shardingValueB.mod(new BigInteger("2"))).add(new BigInteger("1"));
        // 拼接表名称: t_order_1或者t_order_2
        String key = logicTableName + "_" + resB;
        // 判断表名称是否合法并返回
        if (availableTargetNames.contains(key)) {
            return key;
        }
        throw new UnsupportedOperationException("route " + key + " is not supported ,please check your config");
    }
}
